package space.panker916.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import space.panker916.pojo.DiscussPost;
import space.panker916.pojo.Page;
import space.panker916.service.ElasticsearchService;
import space.panker916.service.LikeService;
import space.panker916.service.UserService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static space.panker916.utils.Constants.ENTITY_TYPE_POST;

@Controller
public class SearchController {
    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @GetMapping("/search")
    public String search(String keyword, Page page, Model model) {
        SearchHits<DiscussPost> searchDiscussPost = elasticsearchService.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit());

        page.setPath("/search?keyword=" + keyword);
        page.setRows(searchDiscussPost == null ? 0 : (int) searchDiscussPost.getTotalHits());
        model.addAttribute("page", page);

        // 先处理高亮，然后聚合数据
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        for (SearchHit<DiscussPost> hit : searchDiscussPost) {
            // 处理高亮
            DiscussPost discussPost = hit.getContent();
            List<String> title = hit.getHighlightField("title");
            List<String> content = hit.getHighlightField("content");

            if (!title.isEmpty()) discussPost.setTitle(title.get(0));
            if (!content.isEmpty()) discussPost.setContent(content.get(0));

            // 聚合数据
            Map<String, Object> map = new HashMap<>();
            // 帖子
            map.put("post", discussPost);
            // 作者
            map.put("user", userService.findUserById(discussPost.getUserId()));
            // 点赞数量
            map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId()));

            discussPosts.add(map);
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);

        return "/site/search";
    }
}
